import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

// 封装easyloading
class YSHHUDManager {
  // 配置HUD(在runApp中调用)
  static void configHUDManager() {
    EasyLoading.instance
      ..displayDuration = const Duration(milliseconds: 2000)
      ..indicatorType = EasyLoadingIndicatorType.ring
      ..loadingStyle = EasyLoadingStyle.dark
      ..maskType = EasyLoadingMaskType.black
      ..indicatorSize = 45.0
      ..radius = 10.0
      ..progressColor = Colors.yellow
      ..backgroundColor = Colors.green
      ..indicatorColor = Colors.yellow
      ..textColor = Colors.yellow
      ..maskColor = Colors.blue.withOpacity(0.5)
      ..userInteractions = false
      ..dismissOnTap = false
      ..customAnimation = YSHHUDCustomAnimation();
  }

  // 初始化HUD(在MaterialApp中的builder调用)
  static TransitionBuilder initHUDTool({TransitionBuilder? builder}) {
    return EasyLoading.init(builder: builder);
  }

  // 显示加载动画(需手动取消)
  static Future<void> showLoading({String? text}) {
    if (YSHHUDManager.isShow) YSHHUDManager.dismiss();
    return EasyLoading.show(status: text ?? '加载中...');
  }

  // 提示成功信息
  static Future<void> showSuccess({text = '操作成功', Duration? duration}) {
    if (YSHHUDManager.isShow) YSHHUDManager.dismiss();
    return EasyLoading.showSuccess(text, duration: duration);
  }

  // 提示错误信息
  static Future<void> showError({text = '发生错误', Duration? duration}) {
    if (YSHHUDManager.isShow) YSHHUDManager.dismiss();
    return EasyLoading.showError(text, duration: duration);
  }

  // 提示普通信息
  static Future<void> showInfo(String text, {Duration? duration}) {
    if (YSHHUDManager.isShow) YSHHUDManager.dismiss();
    return EasyLoading.showInfo(text, duration: duration);
  }

  // 提示Toast信息
  static Future<void> showToast(String text,
      {Duration? duration, EasyLoadingToastPosition? toastPosition}) {
    if (YSHHUDManager.isShow) YSHHUDManager.dismiss();
    return EasyLoading.showToast(text,
        duration: duration, toastPosition: toastPosition);
  }

  // 显示环形进度条(进度progress范围0-1,超过时进度条消失)
  static Future<void> showProgress(double progress, {String? text}) {
    if (progress > 1.0) YSHHUDManager.dismiss();
    String status = text ?? '已完成...${(progress * 100).toStringAsFixed(0)}%';
    return EasyLoading.showProgress(progress, status: status);
  }

  // 当前是否有HUD正在显示
  static bool get isShow => EasyLoading.isShow;

  // 隐藏HUD
  static Future<void> dismiss({animation = true}) {
    return EasyLoading.dismiss(animation: animation);
  }
}

class YSHHUDCustomAnimation extends EasyLoadingAnimation {
  YSHHUDCustomAnimation();
  @override
  Widget buildWidget(
    Widget child,
    AnimationController controller,
    AlignmentGeometry alignment,
  ) {
    return Opacity(
      opacity: controller.value,
      child: RotationTransition(
        turns: controller,
        child: child,
      ),
    );
  }
}
